/**
 * 创建场景
 * 布置场景
 */
let APP = function () {
    let scene = new THREE.Scene();//定义场景
    let camera = [];//定义相机
    let point = new THREE.PointLight(0xffffff);//定义光源
    let ambient = new THREE.AmbientLight(0xffffff);//定义环境光
    let w = window.innerWidth;//场景宽
    let h = window.innerHeight;//场景高
    let k = w / h;
    let s = 200; //三维场景显示范围控制系数，系数越大，显示的范围越大
    let fbxLoader = new THREE.FBXLoader();//fbx加载器
    let mixer = null;
    let Animi = null;//动画存储对象
    let renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
    let selectObject;
    let controls = null;
    this.init = function () {//初始化程序
        renderer.setPixelRatio(window.devicePixelRatio);
        document.body.appendChild(renderer.domElement); //body元素中插入canvas对象
        //point.position.set(100, 200, 300); //点光源位置
        //  scene.add(point);//将点光源添加到场景中
        scene.add(ambient);//添加环境光

        //创建摄像机


        camera = new THREE.PerspectiveCamera(60, w / h, 0.1, 1000);
        //camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
        camera.updateProjectionMatrix();
        camera.position.set(200, 300, 200); //设置相机位置
        //camera.lookAt(scene.position); //设置相机方向(指向的场景对象)
        camera.lookAt(new THREE.Vector3(0, 0, 0));


        // controls = new THREE.OrbitControls(camera, renderer.domElement);
        // controls.maxPolarAngle = Math.PI * 0.45;
        // controls.minDistance = 10;
        // controls.maxDistance = 750;
        // controls.update();





        addEventListener('click', this.onMouseClick, false);


        /**
         * 调试区域
         */
        //this.createThing();
        this.render();//渲染空间
        this.createGlobe();
        //this.loadOBJ();
        //this.modelLoad();
        // this.createFloor();
    };
    /**
     * 添加星星
     */
    this.createStar = function () {


    };


    /**
     * 移动摄像头
     */
    this.moveCamera = function () {

        let timer = setInterval(move, 200);

        function move() {


        }


    };


    /**
     * 创建草地平面
     */
    this.createFloor = function () {
        var geometry = new THREE.PlaneGeometry(1000, 1000); //矩形平面
        // 加载草地纹理贴图
        var texture = new THREE.TextureLoader().load("static/img/grass.jpg");
        // 设置纹理的重复模式
        texture.wrapS = THREE.RepeatWrapping;
        texture.wrapT = THREE.RepeatWrapping;
        // uv两个方向纹理重复数量
        texture.repeat.set(10, 10);
        var material = new THREE.MeshLambertMaterial({
            //color: 0x777700,
            map: texture,
        });
        var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
        scene.add(mesh); //网格模型添加到场景中
        mesh.rotateX(-Math.PI / 2);

    };
    /**
     * 添加运行轨迹
     */
    this.createTrack = function (position) {

        const track = new THREE.Mesh(new THREE.RingGeometry(position, position + 0.05, 64, 1), new THREE.MeshBasicMaterial({
            side: THREE.DoubleSide
        }));
        track.rotation.x = -Math.PI / 2;
        scene.add(track);
        AP.xuanzhuan(track);
    };
    /**
     * 点击事件
     */
    this.onMouseClick = function (event) {

        // 获取 raycaster 和所有模型相交的数组，其中的元素按照距离排序，越近的越靠前
        var intersects = AP.getIntersects(event);

        // 获取选中最近的 Mesh 对象
        if (intersects.length != 0 && intersects[0].object instanceof THREE.Mesh) {
            selectObject = intersects[0].object;
            AP.changeMaterial(selectObject);
        } else {
            console.log("未选中 Mesh!");


        }
    };

    // 改变对象材质属性
    this.changeMaterial = function (object) {
        console.log(object);

        var material = new THREE.MeshLambertMaterial({
            color: 0x80FF00 * Math.random(),
            transparent: object.material.transparent ? false : true,
            opacity: 0.8
        });
        object.material = material;
        //renderer.render(scene, camera);
    };

    // 获取与射线相交的对象数组
    this.getIntersects = function (event) {
        event.preventDefault();
        console.log("event.clientX:" + event.clientX);
        console.log("event.clientY:" + event.clientY);

        // 声明 raycaster 和 mouse 变量
        var raycaster = new THREE.Raycaster();
        var mouse = new THREE.Vector2();

        // 通过鼠标点击位置,计算出 raycaster 所需点的位置,以屏幕为中心点,范围 -1 到 1
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        //通过鼠标点击的位置(二维坐标)和当前相机的矩阵计算出射线位置
        raycaster.setFromCamera(mouse, camera);

        // 获取与射线相交的对象数组，其中的元素按照距离排序，越近的越靠前
        var intersects = raycaster.intersectObjects(scene.children);

        //返回选中的对象
        return intersects;
    };


    /**
     * 创建球体
     */
    this.createGlobe = function () {

        this.createTrack(200);
        this.xuanzhuanFirst();
        let box = new THREE.SphereGeometry(100, 100, 100);
        //创建纹理贴图
        let textureLoader = new THREE.TextureLoader();
        textureLoader.load('static/img/earth_bg.jpg', function (texture) {
            var material = new THREE.MeshLambertMaterial({
                map: texture
            });
            var mesh = new THREE.Mesh(box, material); //网格模型对象Mesh
            mesh.scale.set(1, 1, 1);
            mesh.position.set(0, 0, 0);
            scene.add(mesh);
            AP.xuanzhuan(mesh);
            // let T0 = new Date();//上次时间
            // function render() {
            //     let T1 = new Date();//本次时间
            //     let t = T1 - T0;//时间差
            //     T0 = T1;//把本次时间赋值给上次时间
            //     requestAnimationFrame(render);
            //    // renderer.render(scene, camera);//执行渲染操作
            //     mesh.rotateY(0.0001 * t);//旋转角速度0.001弧度每毫秒
            //     // mesh.translateX(0.15 * t);
            //
            // }
            //
            // render();

            // camera.position.set(400, 500, 400);
            // camera.lookAt();


        });


        scene.background = new THREE.Color().setHSL(0.51, 0.4, 0.01);
        scene.fog = new THREE.Fog(scene.background, 3500, 15000);

        this.createSun();
        // let material=new THREE.MeshLambertMaterial({
        //     color: 0x2222222, //颜色
        //     dashSize: 1,//显示线段的大小。默认为3。
        //     gapSize: 15,//间隙的大小。默认为1
        // });
        // // let mash=new THREE.Mesh(box,material);

        // var line = new THREE.Line(box, material); //线模型对象
//  computeLineDistances方法  计算LineDashedMaterial所需的距离数组
//         line.computeLineDistances();
//         scene.add(line);


        // let line1=line.clone();
        // scene.add(line1);
        // line1.position.set(200,0,-100);
        // line1.scale.set(0.8,0.8,0.2);


    };
    this.xuanzhuanFirst = function () {

        let len = this.randomNum(10, 20);//轨道数量
        console.log(len);
        for (let i = 0; i < len; i++) {
            let position = this.randomNum(10, 200);
            console.log(position);
            const track = new THREE.Mesh(new THREE.RingGeometry(position, position + 0.05, 64, 1), new THREE.MeshBasicMaterial({
                side: THREE.DoubleSide
            }));
            track.rotation.x = -Math.PI / 2;
            scene.add(track);
            AP.trackAnimi(track);

        }
    };
    /**
     * 轨道随机动画
     */
    this.trackAnimi = function (obj) {
        let T0 = new Date();//上次时间
        let r = this.randomNum(0.0001, 0.001);

        function render() {
            let T1 = new Date();//本次时间
            let t = T1 - T0;//时间差
            T0 = T1;//把本次时间赋值给上次时间
            requestAnimationFrame(render);
            obj.rotateY(r * t);//旋转角速度0.001弧度每毫秒


        }

        render();
    };

    /**
     * 取随机数
     * @param min
     * @param max
     */
    this.randomNum = function (min, max) {
        let range = max - min;
        let rand = Math.random();
        let num = min + Math.round(rand * range);
        return num;

    };

    this.xuanzhuan = function (obj) {

        let T0 = new Date();//上次时间
        function render() {
            let T1 = new Date();//本次时间
            let t = T1 - T0;//时间差
            T0 = T1;//把本次时间赋值给上次时间
            requestAnimationFrame(render);
            // renderer.render(scene, camera);//执行渲染操作
            obj.rotateY(0.0001 * t);//旋转角速度0.001弧度每毫秒
            // mesh.translateX(0.15 * t);

        }

        render();

    };


    /**
     * 创建太阳
     */
    this.createSun = function () {
        // var textureLoader = new THREE.TextureLoader();
        //
        // var textureFlare0 = textureLoader.load( "static/img/lensflare/lensflare0.png" );
        // var textureFlare2 = textureLoader.load( "static/img/lensflare/lensflare2.png" );
        // var textureFlare3 = textureLoader.load( "static/img/lensflare/lensflare3.png" );
        //
        // addLight( 0.55, 0.9, 0.5, 5000, 0, -1000 );
        // addLight( 0.08, 0.8, 0.5,    0, 0, -1000 );
        // addLight( 0.995, 0.5, 0.9, 5000, 5000, -1000 );
        //
        // function addLight( h, s, l, x, y, z ) {
        //
        //     var light = new THREE.PointLight( 0xffffff, 1.5, 2000 );
        //     light.color.setHSL( h, s, l );
        //     light.position.set( x, y, z );
        //     scene.add( light );
        //
        //     var flareColor = new THREE.Color( 0xffffff );
        //     flareColor.setHSL( h, s, l + 0.5 );
        //
        //     var lensFlare = new THREE.LensFlare( textureFlare0, 700, 0.0, THREE.AdditiveBlending, flareColor );
        //
        //     lensFlare.add( textureFlare2, 512, 0.0, THREE.AdditiveBlending );
        //     lensFlare.add( textureFlare2, 512, 0.0, THREE.AdditiveBlending );
        //     lensFlare.add( textureFlare2, 512, 0.0, THREE.AdditiveBlending );
        //
        //     lensFlare.add( textureFlare3, 60, 0.6, THREE.AdditiveBlending );
        //     lensFlare.add( textureFlare3, 70, 0.7, THREE.AdditiveBlending );
        //     lensFlare.add( textureFlare3, 120, 0.9, THREE.AdditiveBlending );
        //     lensFlare.add( textureFlare3, 70, 1.0, THREE.AdditiveBlending );
        //
        //     lensFlare.customUpdateCallback = lensFlareUpdateCallback;
        //     lensFlare.position.copy( light.position );
        //
        //     scene.add( lensFlare );
        //
        // }
        //
        //
        // function lensFlareUpdateCallback( object ) {
        //
        //     var f, fl = object.lensFlares.length;
        //     var flare;
        //     var vecX = -object.positionScreen.x * 2;
        //     var vecY = -object.positionScreen.y * 2;
        //
        //
        //     for( f = 0; f < fl; f++ ) {
        //
        //         flare = object.lensFlares[ f ];
        //
        //         flare.x = object.positionScreen.x + vecX * flare.distance;
        //         flare.y = object.positionScreen.y + vecY * flare.distance;
        //
        //         flare.rotation = 0;
        //
        //     }
        //
        //     object.lensFlares[ 2 ].y += 0.025;
        //     object.lensFlares[ 3 ].rotation = object.positionScreen.x * 0.5 + THREE.Math.degToRad( 45 );
        //
        // }

    }

    /**
     * 创建文字
     */
    this.createText = function () {
        // var text = new THREE.FontLoader().load('static/font/gentilis_bold.typeface.json', function(text) {
        //     var gem = new THREE.TextGeometry('xxxxx', {
        //         size: 100, //字号大小，一般为大写字母的高度
        //         height: 10, //文字的厚度
        //         weight: 'normal', //值为'normal'或'bold'，表示是否加粗
        //         font: text, //字体，默认是'helvetiker'，需对应引用的字体文件
        //         style: 'normal', //值为'normal'或'italics'，表示是否斜体
        //         bevelThickness: 1, //倒角厚度
        //         bevelSize: 1, //倒角宽度
        //         curveSegments: 30,//弧线分段数，使得文字的曲线更加光滑
        //         bevelEnabled: true, //布尔值，是否使用倒角，意为在边缘处斜切
        //     });
        //     gem.center();
        //     var mat = new THREE.MeshPhongMaterial({
        //         color: 0xffe502,
        //         specular: 0x009900,
        //         shininess: 30,
        //         shading: THREE.FlatShading
        //     });
        //     var textObj = new THREE.Mesh(gem, mat);
        //     textObj.castShadow = true;
        //     scene.add(textObj);
        //
        // });


    };


    /**
     * 创建物体立方体
     */
    this.createThing = function () {
        //界面的左边临界值
        let pW = 5, pH = 100, pL = 100;
        let letX = -w / 2 + pL / 2;
        let topY = h / 2 - 50;
        console.log("h" + h + " pi " + Math.PI);


        let geometry = new THREE.BoxGeometry(pL, pH, pW);
        let meterial = new THREE.MeshLambertMaterial({
            color: 0x1212121
        });
        let mesh = new THREE.Mesh(geometry, meterial);
        scene.add(mesh);
        mesh.rotateY(Math.PI / 180);
        mesh.position.set(0, 0, 0);
        let data = {
            "src": "wangjibu.top"
        };
        mesh.userData = data;
        this.createText();
        // let text=AP.createText();
        // scene.add(text);


    };

    /**
     * 加载模型
     *
     */
    this.modelLoad = function () {
        fbxLoader.load('fbx/xiongmao.fbx', function (obj) {
            mixer = new THREE.AnimationMixer(obj);
            var AnimationAction = mixer.clipAction(obj.animations[0]);
            // AnimationAction.timeScale = 1; //默认1，可以调节播放速度
            // AnimationAction.loop = THREE.LoopOnce; //不循环播放
            // AnimationAction.clampWhenFinished=true;//暂停在最后一帧播放的状态
            AnimationAction.play();//播放动画

            obj.traverse(function (child) {
                if (child instanceof THREE.Mesh) {
                    //将贴图赋于材质
                    //child.material.map = texture;
                    //重点，没有该句会导致PNG无法正确显示透明效果

                    child.material.emissive = child.material.color;
                    child.material.emissiveMap = child.material.map;
                    child.material.transparent = true;
                }
            });

            obj.scale.set(0.1, 0.1, 0.1);
            scene.add(obj);


            // let T0 = new Date();//上次时间
            // function render1() {
            //     let T1 = new Date();//本次时间
            //     let t = T1 - T0;//时间差
            //     T0 = T1;//把本次时间赋值给上次时间
            //     requestAnimationFrame(render1);
            //     renderer.render(scene, camera);//执行渲染操作
            //     obj.rotateY(0.001 * t);//旋转角速度0.001弧度每毫秒
            // }
            //
            // render1();

        });


    };
    /**
     * 加载obj模型以及贴图渲染
     */
    this.loadOBJ = function () {
        let loaderObj = new THREE.OBJLoader();
        let loaderMtl = new THREE.MTLLoader();

        loaderMtl.load('fbx/nianshou.mtl', function (mater) {

            loaderObj.setMaterials(mater);

            loaderObj.load('fbx/nianshou.obj', function (obj) {
                obj.children[0].material.color.set(0xff0000);
                console.log(obj.children);
                scene.add(obj);

            });

        });


    };

    /**
     * 创建盒子
     */
    this.createBox = function () {
        /**
         * 创建一个球体几何对象
         */
        let geometry = new THREE.BoxGeometry(10, 10, 10); //创建一个立方体几何对象Geometry
        let material = new THREE.MeshLambertMaterial({
            color: 0xffffff
        }); //材质对象Material
        var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
        scene.add(mesh); //网格模型添加到场景中


    };


    /**
     * 创建渲染器对象
     */
    this.render = function () {
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(w, h);//设置渲染区域尺寸
        renderer.setClearAlpha(0);

        //执行渲染操作   指定场景、相机作为参数
        renderer.render(scene, camera);
        requestAnimationFrame(() => {
            renderer.setClearAlpha(0);
            this.render();

        })

    };
    /**
     * 添加控制对象的方法
     */
    this.createControl = function () {


    };
    /**
     * 实时更新动画
     * @param time
     */
    this.update = function () {
        requestAnimationFrame(AP.update);
        renderer.render(scene, camera);

    };

    this.resizeRendererToDisplaySize = function (renderer) {

        const canvas = renderer.domElement;
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        const needResize = canvas.width !== width || canvas.height !== height;
        if (needResize) {
            renderer.setSize(width, height, false);
        }
        return needResize;
    }


};

